import { Sms } from '../../utils/sms.js';
var sms = new Sms();
import { Common } from '../../utils/common.js';
var common = new Common();
import { Shop } from '../shop/shop-model.js';
var shop = new Shop();
import { Config } from '../../utils/config.js';
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
var qqmapsdk = new QQMapWX({
  key: Config.qqmapkey
});
Page({

  data: {
    codeText:'获取验证码',
    cateArr:[],
    cateStr:'请选择行业',
    show_send_code:true,
    args:{
      name:'',
      address:'',
      category_id:1,
      mobile:'',
      business_hours: '8-22点',
      verifyCode:'',
      password:'123456',
      license:'/storage/',
      lat:'',
      lng:''
    },
    need_map: true,
    hiddenMap:true,
    pics: [],//营业执照
    pics2: [],//身份证正反面
    btnText:'提交',
    btnType:'disable',
    shopInfo:{apply_status:-1} //- 代表没有店铺
  },
  onLoad: function (options) {
    //二维码进入
    var id = '';
    if (options.scene) {
      var scene = decodeURIComponent(options.scene);
      var arr = scene.split("=");
      var id = arr[1];
    }
    if (options.pid){
      var id = options.pid;
    }
    if(id){
      wx.setStorageSync('shop_invitor', id);
    }
    this.getStatus();
  },
  //店铺申请状态
  getStatus: function () {
    var that = this;
    var params = {};
    var token = wx.getStorageSync('token');
    if(!token){
      wx.showModal({
        title: '提示',
        content: '您正在登录系统，请3秒后点击确定重试！',
        success(res) {
          if (res.confirm) {
            that.getStatus();
          } else if (res.cancel) {
            that.getStatus();
          }
        }
      })
    }
    shop.applyStatus(params, (data) => {
      wx.hideLoading();
      if(data.status == 0){
        if(that.data.need_map){
          that.getLocation();
        }
        return false; //没有店铺，直接填写全部的新信息
      }
      var cate = that.data.cateArr;
      cate.forEach((item, index) => {
        if (data.item.category_id == item.id){
          that.setData({
            index:index,
            cateStr:item.name
          })
        }
      })
      var p = [];
      p.push({url:data.item.license});
      that.setData({
        shopInfo: data.item,
        'args.name': data.item.name,
        'args.address': data.item.address,
        'args.category_id': data.item.category_id,
        'args.mobile': data.item.mobile,
        'args.license': data.item.license,
        'args.lat': data.item.lat,
        'args.lng': data.item.lng,
        pics:p
      })
    });
  },
  //行业分类
  getCate:function(){
    wx.showLoading({
      title: '加载中...',
    })
    var that = this;
    var params = {};
    shop.category(params, (data) => {
      that.setData({
        cateArr : data.items
      })
      this.getStatus();
    });
  },
  pickerChange: function (e) {
    var cateArr = this.data.cateArr;
    var index = e.detail.value;
    var cateStr = cateArr[index].name
    this.setData({
      index,
      cateStr,
      'args.category_id': cateArr[index].id
    })
  },
  //发送短信验证码
  sendCode: function (e) {
    if (!this.data.args.mobile) {
      wx.showToast({
        title: '请先填写手机号码',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (this.data.args.mobile.length != 11) {
      wx.showToast({
        title: '手机号码不正确',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    this.setData({
      show_send_code: false,
      countDownNum: 60
    });
    this.countDown();
    var params = {
      mobile: this.data.args.mobile,
      scene: 1
    }
    sms.send(params, (data) => {
      if (data.status == 1) {
        wx.showToast({
          title: "验证码已发送到您手机上",
          icon: 'none',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: data.msg,
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  countDown: function () {
    let that = this;
    let countDownNum = that.data.countDownNum;//获取倒计时初始值
    //如果将定时器设置在外面，那么用户就看不到countDownNum的数值动态变化，所以要把定时器存进data里面
    that.setData({
      timer: setInterval(function () {//这里把setInterval赋值给变量名为timer的变量
        //每隔一秒countDownNum就减一，实现同步
        countDownNum--;
        that.setData({
          countDownNum: countDownNum
        })
        //在倒计时还未到0时，这中间可以做其他的事情，按项目需求来
        if (countDownNum == 0) {
          clearInterval(that.data.timer);
          that.setData({
            show_send_code: true
          });
        }
      }, 1000)
    })
  },
  //店名
  nameChange: function (e) {
    var val = e.detail.value;
    this.setData({
      'args.name': val
    });
    this.btnChange();
  },
  //联系电话
  telChange: function (e) {
    var val = e.detail.value;
    this.setData({
      'args.tel': val
    });
  },
  //营业时间
  timeChange: function (e) {
    var val = e.detail.value;
    this.setData({
      'args.business_hours': val
    });
  },
  //地址
  addressChange: function (e) {
    var val = e.detail.value;
    this.setData({
      'args.address': val
    });
    this.btnChange();
  },
  //选择地址
  toMap: function (e) {
    this.setData({
      hiddenMap : false
    })
  },
  hideModal: function (e) {
    this.setData({
      hiddenMap: true
    })
  },
  //移动选点
  moveToLocation: function () {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        var address = res.address + res.name;
        var lat = res.latitude ? res.latitude : '';
        var lng = res.longitude ? res.longitude : '';
        that.setData({
          'args.address': address,
          'args.lat': lat,
          'args.lng': lng
        });
      },
      fail: function (err) {
        console.log(err)
      }
    });
  },
  //获取用户输入的手机号码内容
  mobileChange: function (e) {
    var val = e.detail.value;
    this.setData({
      'args.mobile': val
    });
    this.btnChange();
  },
  //获取用户输入的登录密码
  passwordChange: function (e) {
    var val = e.detail.value;
    this.setData({
      'args.password': val
    });
    this.btnChange();
  },
  //获取用户输入的验证码内容
  codeChange: function (e) {
    var val = e.detail.value;
    this.setData({
      'args.verifyCode': val
    });
    this.btnChange();
  },
  //判断激活按钮的样式
  btnChange: function () {
    let type = 'disable'
    if (this.data.args.mobile && this.data.args.verifyCode) {
      type = 'sub';
    }
    this.setData({
      btnType: type
    });
  },
  sub:function(){
    var token = wx.getStorageSync('token');
    if (!token) {
      wx.showModal({
        title: '提示',
        content: '您尚未登录，不能申请店铺',
      })
      return false;
    }
    var that = this;
    var params = that.data.args;
    if(!params.name){
      wx.showToast({
        title: "请填写店铺名",
        icon: 'none',
        duration: 2000,
      })
      return false;
    }
    if (!params.address) {
      wx.showToast({
        title: "请填写店铺地址",
        icon: 'none',
        duration: 2000,
      })
      return false;
    }
    // if (!params.category_id) {
    //   wx.showToast({
    //     title: "请选择行业",
    //     icon: 'none',
    //     duration: 2000,
    //   })
    //   return false;
    // }
    if (!params.mobile) {
      wx.showToast({
        title: "请填写手机号",
        icon: 'none',
        duration: 2000,
      })
      return false;
    }
    if (!params.verifyCode) {
      wx.showToast({
        title: "请填写验证码",
        icon: 'none',
        duration: 2000,
      })
      return false;
    }
    if (!params.password) {
      wx.showToast({
        title: "请输入登录密码",
        icon: 'none',
        duration: 2000,
      })
      return false;
    }
    if (this.data.shopInfo.apply_status == 1) {
      wx.showModal({
        title: '您确定要提交吗',
        content: '重新提交信息店铺将会进行重新审核，审核期间店铺将被暂时下架',
        success(res) {
          if (res.confirm) {
            that.sub2();
          } else if (res.cancel) {
            return false;
          }
        }
      })
    }else{
      that.sub2();
    }
  },
  sub2:function(){
    var that = this;
    var params = that.data.args;
    if(this.data.onLoadding) {
      return false;
    }
    var pid = wx.getStorageSync('shop_invitor');
    if(pid){
      params.pid = pid;
    }
    this.setData({ btnText: '提交中...' })
    this.data.onLoadding = true;
    //params.map = that.data.args.lat + "," + that.data.args.lng;
    shop.apply(params, (data) => {
      that.data.onLoadding = false;
      this.setData({ btnText: '提交' })
      if (data.status == 1) {
        wx.showToast({
          title: "申请成功",
          icon: 'success',
          duration: 2000,
          success: function () {
            wx.switchTab({
              url: '../center/center',
            })
          }
        })
      } else {
        wx.showToast({
          title: data.msg,
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  //上传图片开始
  chooseImg: function (e) {
    var url = Config.restUrl;
    url = url.slice(0, url.length - 4);
    var that = this, pics = this.data.pics;
    if (pics.length < 1) {
      wx.chooseImage({
        count: 1, // 最多可以选择的图片张数，默认9
        sizeType: ['original', 'compressed'], 
        sourceType: ['album', 'camera'], 
        success: function (res) {
          that.setData({
            showerr: false
          })
          var tempFilePaths = res.tempFilePaths;
          for (var i = 0; i < tempFilePaths.length; i++) {
            pics.push({url:tempFilePaths[i]});
          }
          wx.showLoading({
            title: '上传中...',
          })
          
          wx.uploadFile({
            url: url + '/upload/images-upload?fileparam=image&thumb=1&width=500&height=500',
            filePath: res.tempFilePaths[0],
            name: 'image',
            formData: {},
            success: function (res) {
              if(res.statusCode != 200){
                wx.showToast({
                  title: '上传失败,图片过大',
                  icon: 'none',
                  duration: 3000
                });
                //pics = []
                that.setData({
                  showerr: true
                })
                return false;
              }
              var data = JSON.parse(res.data);
              if (!data.files){
                wx.showToast({
                  title: '上传失败',
                  icon: 'none',
                  duration: 3000
                });
                //pics = []
                that.setData({
                  showerr: true
                })
              }else{
                that.setData({
                  'args.license': data.files[0].url
                })
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 2000
                });
              }
            }, 
            fail: function (res) {
              wx.showToast({
                title: '上传失败',
                icon: 'none',
                duration: 3000
              });
              //pics = []
              that.setData({
                showerr: true
              })
            },
            complete:function(){
              wx.hideLoading();
            }

          })
          that.setData({
            pics: pics
          })
        },
      });
    } else {
      wx.showToast({
        title: '最多上传1张图片',
        icon: 'none',
        duration: 3000
      });

    }
  },
  //上传图片开始
  chooseImg2: function (e) {
    var url = Config.restUrl;
    url = url.slice(0, url.length - 4);
    var that = this, pics = this.data.pics2;
    if (pics.length < 2) {
      wx.chooseImage({
        count: 2, // 最多可以选择的图片张数，默认9
        sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
        sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          that.setData({
            files: that.data.files.concat(res.tempFilePaths)
          });
          wx.uploadFile({
            url: url + '/upload/images-upload?fileparam=image&thumb=1&width=500&height=500',
            filePath: res.tempFilePaths[0],
            name: 'image',
            formData: {},
            success: function (res) {
              var data = JSON.parse(res.data);
              var url = data.files[0].url;
              // files_url['url'] = files_url['url'].push(data.files[0].url)
              var thumbImg;
              var img = {};
              img.url = url;
              img.thumbImg = data.files[0].thumbImg;
              pics.push(img);
            }
          })
        },
      });
    } else {
      wx.showToast({
        title: '最多上传2张图片',
        icon: 'none',
        duration: 3000
      });

    }
  },
  // 删除图片
  deleteImg: function (e) {
    var that = this;
    var pics = this.data.pics;
    var index = e.currentTarget.dataset.index;
    pics.splice(index, 1);
    this.setData({
      pics: pics,
      'args.license' : ''
    })
  },
  // 删除图片
  deleteImg2: function (e) {
    var that = this;
    var pics = this.data.pics2;
    var index = e.currentTarget.dataset.index;
    pics.splice(index, 1);
    this.setData({
      pics2: pics,
    })
  },
  // 预览图片
  previewImg1: function (e) {
    var index = e.currentTarget.dataset.index;
    var pics = this.data.pics;
    wx.previewImage({
      current: pics[index],
      urls: pics
    })
  },
  // 预览图片
  previewImg2: function (e) {
    var index = e.currentTarget.dataset.index;
    var pics = this.data.pics;
    wx.previewImage({
      current: pics[index],
      urls: pics
    })
  },
  //将图片上传到服务器
  saveImage: function () {
    var that = this;
    var pics = this.data.pics;
    var url = "upload/images-upload?fileparam=" + pics +"& thumb=1 & width=100 & height=100"
    common.upload(url, (data) => {
      this.setData({ btnText: '提交' })
      if (data.status == 1) {
        wx.showToast({
          title: "申请成功",
          icon: 'success',
          duration: 2000,
          success: function () {
            wx.navigateTo({
              url: '../center/center',
            })
          }
        })
      } else {
        wx.showToast({
          title: data.msg,
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  getLocation: function () {
    var that = this;
    // 调用接口
    qqmapsdk.reverseGeocoder({
      success: function (res) {
        that.setData({
          'args.address': res.result.address,
          'args.lat': res.result.location.lat,
          'args.lng': res.result.location.lng
        });
      },
      fail: function (res) {
        //console.log(res);
      },
      complete: function (res) {
        //console.log(res);
      }
    });
  }
})